package cn.memedai.router.matcher;

import android.app.Activity;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;

import androidx.annotation.Nullable;

import java.util.HashMap;
import java.util.Map;

import cn.memedai.router.RouteOptions;

/**
 * <p>本类用于匹配米么私有协议
 *
 * @author gooljim
 * @version [版本号]
 * @see [相关类/方法]
 * @since [产品/模块版本]
 */
public class MmdMatcher extends AbsExplicitMatcher {

    //协议前缀
    private static final String PRIVATE_PROTOC0L_PREFIX = "zhoupu";
    private static final String PRIVATE_PROTOCOL_ACTION_OPEN = "open";
    private static final String KEY_PRIVATE_PROTOC0L_PAGE = "page";

    public MmdMatcher(int priority) {
        super(priority);
    }

    @Override
    public MatcherResult match(Context context, Uri uri, @Nullable Map<String, Class<? extends Activity>> activityTable, RouteOptions routeOptions) {
        MatcherResult matcherResult = MatcherResult.newInstance();
        if (activityTable==null ||activityTable.isEmpty()) {
            return matcherResult;
        }
        //scheme == zhoupu
        if (uri.isRelative() || !uri.getScheme().equalsIgnoreCase(PRIVATE_PROTOC0L_PREFIX)) {
            return matcherResult;
        }
        //host == open and host != empty
        if (isEmpty(uri.getAuthority()) || !uri.getAuthority().equalsIgnoreCase(PRIVATE_PROTOCOL_ACTION_OPEN)) {
            return matcherResult;
        }
        // bundle parser
        if (uri.getQuery() != null) {
            // parse entry from given uri.
            Map<String, String> params = new HashMap<>();
            parseParams(params, uri.getQuery());
            String page = params.get(KEY_PRIVATE_PROTOC0L_PAGE);
            if (isEmpty(page)) {
                return matcherResult;
            }
            Class <? extends Activity> router = activityTable.get(page);
            params.remove(KEY_PRIVATE_PROTOC0L_PAGE);
            if (!params.isEmpty()) {
                Bundle bundle = routeOptions.getBundle();
                if (bundle == null) {
                    bundle = new Bundle();
                    routeOptions.setBundle(bundle);
                }
                for (Map.Entry<String, String> entry : params.entrySet()) {
                    bundle.putString(entry.getKey(), entry.getValue());
                }
            }
            matcherResult.setMatch(true);
            matcherResult.setMatchClass(router);
            return matcherResult;
        }
        return matcherResult;
    }

    /**
     * 剔除path头部和尾部的斜杠/
     *
     * @param path 路径
     * @return 无/的路径
     */
    private String cutSlash(String path) {
        if (path.startsWith("/")) {
            return cutSlash(path.substring(1));
        }
        if (path.endsWith("/")) {
            return cutSlash(path.substring(0, path.length() - 1));
        }
        return path;
    }
}
